﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using CustomersSuppliersBusinessLayer;
using CustomersSuppliersDataLayer;
using System.Collections;
using WebHelper.Helpers;

namespace CustomersSuppliersWebApplication
{
    public partial class WebFormDealersProducts : WebFormBase
    {
        public Guid? Dealer_ID
        {
            get
            {
                return string.IsNullOrEmpty(this.Request[BLDealer.PropertiesNames.Dealer_ID]) ? (Guid?)null : new Guid(this.Request[BLDealer.PropertiesNames.Dealer_ID]);
            }
        }

        public Guid? DealerType_ID
        {
            get
            {
                return string.IsNullOrEmpty(this.Request[BLDealer.PropertiesNames.DealerType_ID]) ? (Guid?)null : new Guid(this.Request[BLDealer.PropertiesNames.DealerType_ID]);
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                InitializeTelerikRequest(this.RadTextBoxSearch, "onkeyup");
                BLDealer dealer = new BLDealer();
                dealer.Dealer_ID = this.Dealer_ID;
                dealer.LoadByIdentifiers();
                this.PageTitle = "منتجات /" + dealer.Dealer_NameAr;

            }
            if (this.DealerType_ID == DealersTypesDictionary.SuppliersAndCustomers)
            {
                GridTemplateColumn column = this.RadGridResults.MasterTableView.GetColumn("Is_Supplier") as GridTemplateColumn;
                column.ReadOnly = false;
            }
            else
            {
                GridTemplateColumn column = this.RadGridResults.MasterTableView.GetColumn("Is_Supplier") as GridTemplateColumn;
                column.ReadOnly = true;
            }
        }
        protected void RadTextBoxSearch_TextChanged(object sender, EventArgs e)
        {
            this.getDealersProducts();
            this.RadGridResults.Rebind();
        }
        protected void RadComboBoxProductsClassifications_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            this.getDealersProducts();
            this.RadGridResults.Rebind();
        }
        protected void RadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            this.getDealersProducts();
        }
        
        protected void RadGridResults_ItemCreated(object sender, GridItemEventArgs e)
        {
            //pager
            if (e.Item is GridPagerItem)
            {
                GridPagerItem item = e.Item as GridPagerItem;
                Button changePageSize = (Button)e.Item.FindControl("ChangePageSizeLinkButton");
                changePageSize.Text = "تغيير";
                Button goTO = (Button)e.Item.FindControl("GoToPageLinkButton");
                goTO.Text = "تغيير";
                Label itesNumberLabel = (Label)e.Item.FindControl("ChangePageSizeLabel");
                itesNumberLabel.Text = "          عدد الصفوف :";
                Label goTOLabel = (Label)e.Item.FindControl("GoToPageLabel");
                goTOLabel.Text = "صفحة :";
                Label ofLabel = (Label)e.Item.FindControl("PageOfLabel");
                ofLabel.Text = "من " + item.Paging.PageCount.ToString();
            }
        }
        protected void RadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            //set default value
            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                //e.Canceled = true;
                //System.Collections.Specialized.ListDictionary newValues = new System.Collections.Specialized.ListDictionary();
                //newValues[BLAddresse.PropertiesNames.Address_NameAr] = "***";
                //e.Item.OwnerTableView.InsertItem(newValues);
            }

        }
        protected void RadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            BLDealer_Product Dealer_Product = new BLDealer_Product();
            Dealer_Product.Dealer_ID = this.Dealer_ID;
            RadComboBox RadComboBoxProducts = (RadComboBox)editedItem.FindControl("RadComboBoxProducts");
            if (RadComboBoxProducts.SelectedValue != "")
            {
                Dealer_Product.Product_ID = new Guid(RadComboBoxProducts.SelectedValue);
            }
            BLDealer_ProductCollection Dealer_ProductCollection = new BLDealer_ProductCollection();
            Dealer_ProductCollection.Template.AddFilter(LogicalOperators.And, BLDealer_Product.PropertiesNames.Dealer_ID, FilterOperators.Equal, Dealer_Product.Dealer_ID, typeof(Guid));
            Dealer_ProductCollection.Template.AddFilter(LogicalOperators.And, BLDealer_Product.PropertiesNames.Product_ID, FilterOperators.Equal, Dealer_Product.Product_ID, typeof(Guid));
            Dealer_ProductCollection.Load();
            if (Dealer_ProductCollection.Count > 0)
            {
                this.ShowNotification("هذا المنتج موجود مسبقا", NotificationIconType.Warning);
                e.Canceled = true;
                return;
            }
            if (this.DealerType_ID == DealersTypesDictionary.Suppliers)
            {
                Dealer_Product.Is_Supplier = 1;
            }
            else if (this.DealerType_ID == DealersTypesDictionary.Customers)
            {
                Dealer_Product.Is_Supplier = 0;
            }
            else if (this.DealerType_ID == DealersTypesDictionary.ServicesProviders)
            {
                Dealer_Product.Is_Supplier = 0;
            }
            RadButton RadButtonIsSupplier = (RadButton)editedItem.FindControl("RadButtonIsSupplier");
            if (RadButtonIsSupplier != null)
            {
                if (RadButtonIsSupplier.Checked)
                {
                    Dealer_Product.Is_Supplier = 1;
                }
                else
                {
                    Dealer_Product.Is_Supplier = 0;
                }
            }

            Dealer_Product.AutoSave();
            if (Dealer_Product.Error == null)
            {
                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            BLDealer_Product Dealer_Product = new BLDealer_Product();
            Dealer_Product.ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLDealer_Product.PropertiesNames.ID].ToString());
            Dealer_Product.LoadByIdentifiers();
            Dealer_Product.Dealer_ID = this.Dealer_ID;
            RadComboBox RadComboBoxProducts = (RadComboBox)editedItem.FindControl("RadComboBoxProducts");
            if (RadComboBoxProducts.SelectedValue != "")
            {
                Dealer_Product.Product_ID = new Guid(RadComboBoxProducts.SelectedValue);
            }
            BLDealer_ProductCollection Dealer_ProductCollection = new BLDealer_ProductCollection();
            Dealer_ProductCollection.Template.AddFilter(LogicalOperators.And, BLDealer_Product.PropertiesNames.Dealer_ID, FilterOperators.Equal, Dealer_Product.Dealer_ID, typeof(Guid));
            Dealer_ProductCollection.Template.AddFilter(LogicalOperators.And, BLDealer_Product.PropertiesNames.Product_ID, FilterOperators.Equal, Dealer_Product.Product_ID, typeof(Guid));
            Dealer_ProductCollection.Load();
            if (Dealer_ProductCollection.Count > 0 && Dealer_ProductCollection[0].ID != Dealer_Product.ID)
            {
                this.ShowNotification("هذا المنتج موجود مسبقا", NotificationIconType.Warning);
                e.Canceled = true;
                return;
            }

            if (this.DealerType_ID == DealersTypesDictionary.Suppliers)
            {
                Dealer_Product.Is_Supplier = 1;
            }
            else if (this.DealerType_ID == DealersTypesDictionary.Customers)
            {
                Dealer_Product.Is_Supplier = 0;
            }
            else if (this.DealerType_ID == DealersTypesDictionary.ServicesProviders)
            {
                Dealer_Product.Is_Supplier = 0;
            }
            RadButton RadButtonIsSupplier = (RadButton)editedItem.FindControl("RadButtonIsSupplier");
            if (RadButtonIsSupplier != null)
            {
                if (RadButtonIsSupplier.Checked)
                {
                    Dealer_Product.Is_Supplier = 1;
                }
                else
                {
                    Dealer_Product.Is_Supplier = 0;
                }
            }
            Dealer_Product.AutoSave();
            if (Dealer_Product.Error == null)
            {
                this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحفظ", NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            BLDealer_Product Dealer_Product = new BLDealer_Product();
            Dealer_Product.ID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex][BLDealer_Product.PropertiesNames.ID].ToString());
            Dealer_Product.DeleteByIdentifiers();
            if (Dealer_Product.Error == null)
            {
                this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
            }
            else
            {
                this.ShowNotification("حدث خطا اثناء الحذف", NotificationIconType.Error);
                return;
            }
        }
        protected void RadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                RadButton RadButtonIsSupplierDisplay = (RadButton)e.Item.FindControl("RadButtonIsSupplierDisplay");
                if (e.Item.ItemIndex != -1)
                {
                    BLDealer_Product Dealer_Product = (BLDealer_Product)e.Item.DataItem;
                    RadButtonIsSupplierDisplay.Checked = Dealer_Product.Is_Supplier == 1;
                }
            }
            if (e.Item is GridEditableItem && e.Item.IsInEditMode)
            {
                //combobox Products
                RadComboBox RadComboBoxProducts = (RadComboBox)e.Item.FindControl("RadComboBoxProducts");
                BLProductCollection productCollection = new BLProductCollection(CashVariables.ProductCollection);
                for (int i = 0; i < productCollection.Count; i++)
                {
                    int index = CashVariables.ProductsClassificationCollection.FindByIentifier(productCollection[i].ProductClassification_ID);
                    if (index != -1)
                    {
                        productCollection[i].ProductClassification_NameAr = CashVariables.ProductsClassificationCollection[index].ProductClassification_NameAr;
                    }
                }
                RadComboBoxProducts.DataSource = productCollection;
                RadComboBoxProducts.DataTextField = "Product_NameTotal";
                RadComboBoxProducts.DataValueField = BLProduct.PropertiesNames.Product_ID;
                RadComboBoxProducts.DataBind();
                if (e.Item.ItemIndex != -1)
                {
                    BLDealer_Product Dealer_Product = (BLDealer_Product)e.Item.DataItem;
                    RadComboBoxProducts.SelectedValue = Dealer_Product.Product_ID.ToString();
                }

                //RadButtonIsSupplier
                RadButton RadButtonIsSupplier = (RadButton)e.Item.FindControl("RadButtonIsSupplier");
                if (RadButtonIsSupplier != null)
                {
                    if (e.Item.ItemIndex != -1)
                    {
                        BLDealer_Product Dealer_Product = (BLDealer_Product)e.Item.DataItem;
                        RadButtonIsSupplier.Checked = Dealer_Product.Is_Supplier == 1;
                    }
                }
            }
        }


        private void getDealersProducts()
        {
            BLDealer_ProductCollection Dealer_ProductCollection = new BLDealer_ProductCollection();
            //dealer id
            Dealer_ProductCollection.Template.AddFilter(LogicalOperators.And, BLDealer_Product.PropertiesNames.Dealer_ID, FilterOperators.Equal, this.Dealer_ID, typeof(Guid));
            //load
            Dealer_ProductCollection.Load();
            
            for (int i = 0; i < Dealer_ProductCollection.Count; i++)
            {
                int indexProduct = CashVariables.ProductCollection.FindByIentifier(Dealer_ProductCollection[i].Product_ID);
                if (indexProduct != -1)
                {
                    Dealer_ProductCollection[i].Product_NameAr = CashVariables.ProductCollection[indexProduct].Product_NameAr;
                    int indexClassification = CashVariables.ProductsClassificationCollection.FindByIentifier(CashVariables.ProductCollection[indexProduct].ProductClassification_ID);
                    if (indexClassification != -1)
                    {
                        Dealer_ProductCollection[i].ProductClassification_NameAr = CashVariables.ProductsClassificationCollection[indexClassification].ProductClassification_NameAr;
                    }
                }
            }

            //serch filter with linq
            Dealer_ProductCollection=new BLDealer_ProductCollection (from i in Dealer_ProductCollection 
                                                                     where StringHelper.ToUniqueStatement(i.Product_NameTotal).Contains( StringHelper.ToUniqueStatement(this.RadTextBoxSearch.Text))
                                                                     select i);
            
            this.RadGridResults.DataSource = Dealer_ProductCollection;
            this.RadGridResults.MasterTableView.DataKeyNames = BLDealer_Product.PropertiesNames.Identifiers;
        }

    }
}